package com.whpost.service.zhdt.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class DistrictJsonSaver {

    // 固定保存目录（可根据需要修改）
    private static final String FIXED_SAVE_DIR = "D:/amap_json_data/";
    // 高德API Key（建议提取为常量，方便维护）
    private static final String AMAP_KEY = "10b7637dc308aa895035748ca90be008";

    /**
     * 访问高德API获取指定区域JSON数据并保存到固定目录
     * @param keywords 行政区名称（如"江汉区"）
     * @param city 城市名称（如"武汉市"）
     * @param fileName 保存的文件名（如jianghan.json）
     * @throws IOException IO异常
     */
    public static void saveDistrictJson(String keywords, String city, String fileName) throws IOException {
        // 1. 创建固定目录（不存在则创建）
        File saveDirectory = new File(FIXED_SAVE_DIR);
        if (!saveDirectory.exists()) {
            boolean dirCreated = saveDirectory.mkdirs();
            if (!dirCreated) {
                throw new IOException("无法创建保存目录：" + FIXED_SAVE_DIR);
            }
        }

        // 2. 对中文参数进行URL编码并拼接API请求URL
        String encodedKeywords = URLEncoder.encode(keywords, StandardCharsets.UTF_8);
        String encodedCity = URLEncoder.encode(city, StandardCharsets.UTF_8);

        String apiUrl = String.format(
                "https://restapi.amap.com/v3/config/district?key=%s&keywords=%s&city=%s&extensions=all&subdistrict=0",
                AMAP_KEY, encodedKeywords, encodedCity
        );

        URL url = new URL(apiUrl);
        HttpURLConnection connection = null;

        try {
            // 3. 建立HTTP连接
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 连接超时5秒
            connection.setReadTimeout(5000);    // 读取超时5秒
            connection.setRequestProperty("Accept-Charset", "UTF-8");

            // 4. 检查响应状态
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("API请求失败，响应码：" + responseCode + "，消息：" + connection.getResponseMessage());
            }

            // 5. 读取API返回的JSON数据并写入文件
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                 BufferedWriter writer = new BufferedWriter(new FileWriter(new File(saveDirectory, fileName), StandardCharsets.UTF_8))) {

                String line;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                }
                System.out.println("JSON文件保存成功！路径：" + saveDirectory.getAbsolutePath() + File.separator + fileName);
                System.out.println("请求的API地址：" + apiUrl); // 可选：打印请求地址用于调试
            }

        } finally {
            // 6. 关闭连接
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    // 测试方法
    public static void main(String[] args) {
        try {
            // 调用方法，传入行政区名称、城市名称、文件名参数
            saveDistrictJson("江汉区", "武汉市", "jianghan.json");
            // 示例：获取其他区域数据
            // saveDistrictJson("武昌区", "武汉市", "wuchang.json");
        } catch (IOException e) {
            System.err.println("保存JSON文件时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
}